package com.starnet.yarnmonitor.security.filter;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.starnet.yarnmonitor.security.utils.JwtLoginToken;
import com.starnet.yarnmonitor.security.utils.JwtUtil;
import com.starnet.yarnmonitor.security.utils.RedisCache;
import com.starnet.yarnmonitor.yarn.vo.result.Result;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @Data: 2019/10/30
 * @Des: Token有效性验证拦截器
 */
@Component
public class JwtTokenFilter extends OncePerRequestFilter {
@Autowired
    RedisCache redisCache;
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        //        if (httpServletRequest.getRequestURI().equals("/yarn/cluster/nodes"))
//        {    filterChain.doFilter(httpServletRequest, httpServletResponse);}
        try {
            String token = httpServletRequest.getHeader("token");
            if (StringUtils.isEmpty(token)) {
                throw new Exception("未登录，请登陆后请求");
            }

            Claims claims = JwtUtil.parseJWT(token);
            if (JwtUtil.isTokenExpired(claims)) {
                throw new Exception("登陆已失效，请重新登陆");
            }



            //把权限解析出来
            User user = JSONObject.parseObject(claims.getSubject(), User.class);
            JSONObject jsonObject = JSONObject.parseObject(claims.getSubject());
            String authorities = jsonObject.getString("authorities");
            List<SimpleGrantedAuthority> grantedAuthorities = JSONArray.parseArray(authorities, SimpleGrantedAuthority.class);
            //去redis看看有没有这个token
            String cacheObject = redisCache.getCacheObject("login:" + user.getUsername());
            if (cacheObject==null){
                throw new Exception("该账号已退出，请重新登录");
            }
            if (!cacheObject.equals(token)){
                throw new Exception("账号异地登录，已下线，请重新登录");
            }
            JwtLoginToken jwtLoginToken = new JwtLoginToken(user, "", grantedAuthorities);
            jwtLoginToken.setDetails(new WebAuthenticationDetails(httpServletRequest));
            SecurityContextHolder.getContext().setAuthentication(jwtLoginToken);
            filterChain.doFilter(httpServletRequest, httpServletResponse);
        } catch (Exception e) {
            httpServletResponse.setContentType("application/json;charset=UTF-8");
            Result result = Result.fail(e.getMessage());
            httpServletResponse.getWriter().write(JSON.toJSONString(result));
            return;
        }

    }

}
